package com.hqq.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * ClassUtil
 * 类帮助类
 * 用于获得ClassLoader,加载类和加载指定包下的所有类
 * Created by heqianqian on 2017/7/19.
 */
public class ClassUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

    /**
     * 获取类加载器
     *
     * @return ClassLoader
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     *
     * @param className     类名
     * @param isInitialized 是否初始化
     * @return Class
     */
    public static Class<?> loadClass(String className, boolean isInitialized) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className, isInitialized, getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return clazz;
    }

    /**
     * 获取指定包下的所有类
     * 思路:根据路径读取jar和class文件 并根据类文件加载类
     *
     * @param packageName 包名
     * @return Set<Class>
     */
    public static Set<Class<?>> getClassSet(String packageName) {
        Set<Class<?>> classSet = new HashSet<>();
        try {
            //获得所有文件的url地址
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            //迭代所有的url路径
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();
                    if (protocol.equals("file")) {//如果是文件
                        String packagePath = url.getPath().replaceAll("%20", " ");
                        addClass(classSet, packagePath, packageName);
                    } else if (protocol.equals("jar")) {//如果是jar包
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (jarURLConnection != null) {
                            //获得jar文件
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (jarFile != null) {
                                Enumeration<JarEntry> entries = jarFile.entries();
                                while (entries.hasMoreElements()) {
                                    JarEntry jarEntry = entries.nextElement();
                                    String jarName = jarEntry.getName();
                                    if (jarName.endsWith(".class")) {//找到class文件
                                        String className = jarName.substring(0, jarName.lastIndexOf(".")).replaceAll("/", ".");
                                        addToClass(classSet, className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return classSet;
    }

    private static void addClass(Set<Class<?>> classSet, String packagePath, final String packageName) {
        //获取包目录下的所有文件
        final File[] files = new File(packagePath).listFiles(pathname -> ((pathname.isFile() && pathname.getName().endsWith(".class")) || pathname.isDirectory()));
        //遍历文件
        assert files != null;
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {//如果是文件
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (StringUtil.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                }
                addToClass(classSet, className);
            } else {
                String subPackagePath = fileName;
                if (StringUtil.isNotEmpty(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if (StringUtil.isNotEmpty(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass(classSet, subPackagePath, subPackageName);
            }
        }
    }

    /**
     * 加载类
     */
    private static void addToClass(Set<Class<?>> classSet, String className) {
        Class<?> aClass = loadClass(className, false);
        classSet.add(aClass);
    }

}
